package com.example.es.controller;

import com.example.es.entity.UsrDoc;
import com.example.es.service.UsrService;
import lombok.RequiredArgsConstructor;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.web.PageableDefault;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/usr")
@RequiredArgsConstructor
public class UsrController {

    private final UsrService service;

    @PostMapping
    public UsrDoc create(@RequestBody UsrDoc doc) {
        return service.save(doc);
    }

    @GetMapping("/{usrId}")
    public ResponseEntity<UsrDoc> get(@PathVariable String usrId) {
        return service.findById(usrId).map(ResponseEntity::ok).orElse(ResponseEntity.notFound().build());
    }

    @GetMapping
    public Page<UsrDoc> list(@PageableDefault(size = 10) Pageable pageable) {
        return service.findAll(pageable);
    }

    @PutMapping("/{usrId}")
    public UsrDoc update(@PathVariable String usrId, @RequestBody UsrDoc doc) {
        doc.setUsrId(usrId);   // 确保主键一致
        return service.update(doc);
    }

    @DeleteMapping("/{usrId}")
    public void delete(@PathVariable String usrId) {
        service.deleteById(usrId);
    }

    /**
     * GET /usr/search?ageFrom=1&ageTo=25&dateFrom=2024-08-01&dateTo=2025-10-01&page=0&size=10
     */
    @GetMapping("/search")
    public Page<UsrDoc> search(@RequestParam(defaultValue = "1") Integer ageFrom, @RequestParam(defaultValue = "25") Integer ageTo, @RequestParam(defaultValue = "2024-08-01") String dateFrom, @RequestParam(defaultValue = "2025-10-01") String dateTo, @RequestParam(required = false) String name, @PageableDefault(size = 10, sort = "joinDate,desc") Pageable pageable) {

        if (name == null || name.isBlank()) {
            return service.search(ageFrom, ageTo, dateFrom, dateTo, pageable);
        }
        return service.search(ageFrom, ageTo, dateFrom, dateTo, name, pageable);
    }

    /**
     * GET /usr/age1?min=10&max=25&page=0&size=10&sort=usrNm,asc
     */
    @GetMapping("/age1")
    public Page<UsrDoc> searchByAge(@RequestParam(defaultValue = "10") Integer min, @RequestParam(defaultValue = "25") Integer max, @PageableDefault(size = 10) Pageable pageable) {
        return service.searchByAge1(min, max, pageable);
    }

    /**
     * GET /usr/age2?min=10&max=25&page=0&size=10&sort=usrNm,asc
     */
    @GetMapping("/age2")
    public Page<UsrDoc> searchByAge2(@RequestParam(defaultValue = "10") Integer min, @RequestParam(defaultValue = "25") Integer max, @PageableDefault(size = 10) Pageable pageable) {
        return service.searchByAge2(min, max, pageable);
    }

}